package com.example.myapplication.part19;

import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.R;

public class TextViewActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_view);

        TextView textView1 = findViewById(R.id.textView1);
        TextView textView2 = findViewById(R.id.textView2);
        TextView textView3 = findViewById(R.id.textView3);
        TextView textView4 = findViewById(R.id.textView4);

        setupDraggable(textView1);
        setupDraggable(textView2);
        setupDraggable(textView3);
        setupDraggable(textView4);
    }

    private void setupDraggable(final View view) {
        final float[] startX = {0};
        final float[] startY = {0};
        final boolean[] isDragging = {false};
        final Runnable longPressRunnable = new Runnable() {
            @Override
            public void run() {
                isDragging[0] = true; // 开始拖动
            }
        };

        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startX[0] = event.getRawX();
                        startY[0] = event.getRawY();
                        isDragging[0] = false;
                        v.postDelayed(longPressRunnable, 200); // 500ms长按
                        return true;
                    case MotionEvent.ACTION_MOVE:
                        if (!isDragging[0]) {
                            v.removeCallbacks(longPressRunnable); // 取消长按检测
                        } else {
                            // 计算偏移并移动视图
                            float deltaX = event.getRawX() - startX[0];
                            float deltaY = event.getRawY() - startY[0];
                            v.setX(v.getX() + deltaX);
                            v.setY(v.getY() + deltaY);
                            startX[0] = event.getRawX(); // 更新起始点避免累积
                            startY[0] = event.getRawY();
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        v.removeCallbacks(longPressRunnable); // 停止检测
                        if (isDragging[0]) {
                            // 拖动结束后的逻辑（如吸附）
                        }
                        isDragging[0] = false;
                        return true;
                }
                return false;
            }
        });
    }
}